import socket
import select
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = ('', 5888)
s.bind(addr)
s.listen(128)
epoll = select.epoll()
# 监听服务器本身而不是new_client，s本身就有缓冲区，有链接时缓冲区就有数据
epoll.register(s.fileno(), select.EPOLLIN)
epoll.register(sys.stdin, select.EPOLLIN)
client_dict = {}
while True:
    evernts = epoll.poll()
    for fd,event in evernts:
        if fd == s.fileno():
            print(event)
            new_client, arrd = s.accept()
            print(arrd)
            #在accept后，应正确更新client_dict
            client_dict[new_client.fileno()] = new_client
            epoll.register(new_client.fileno(), select.EPOLLIN)
        else:
            dict_content = client_dict.get(fd)

            if dict_content and dict_content.fileno()==fd:
                data = dict_content.recv(1000)
                if data:
                    print(data.decode('utf8'))
                    name = (str(dict_content.fileno())+':').encode('utf8')
                    for other_client in client_dict.values():
                        if other_client is dict_content:
                            continue
                        else:
                            other_client.send(name+data)

                else:
                    del client_dict[fd]
                    epoll.unregister(dict_content.fileno())
                    dict_content.close()

s.close()

